package com.example.zx.theline.lyjh.lyyjh;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.example.zx.theline.pub.CheckInfoActivity;
import com.example.zx.theline.lyjh.pub.JhshCKActivity;
import com.example.zx.theline.R;
import com.loopj.android.http.RequestParams;
import com.scu.miomin.shswiperefresh.core.SHSwipeRefreshLayout;
import com.scu.miomin.shswiperefresh.view.SHListView;

import org.apache.http.Header;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import GsonBean.JhshBean;
import GsonBean.ShyjhxqBean;
import Utils.BackHandlerHelper;
import Utils.DateUtil;
import Utils.MyToast;
import app.MyApplication;
import base.BaseFragment;
import bean.JhshSearchBean;
import network.BaseCallBack;
import network.NetWorkApi;
import network.ObjectHttpResponseHandler;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import views.JhshSearchView;

/**
 * A simple {@link Fragment} subclass.
 * 计划审核月已完成
 */
public class JhshywcFragment extends BaseFragment implements View.OnClickListener {
    private View contentView;

    private SHSwipeRefreshLayout mSHSwipeRefreshLayout;
    private SHListViewAdapter mSHListViewAdapter;
    private SHListView mSHListView;
    private List<JhshBean.RowsBean> mList;
    private TextView mFootTextView;
    private JhshSearchView mJhshSearchView;

    private TextView centerTextView;
    private TextView rightTextView;
    private TextView leftTextView;
    private TextView prev, next;


    //数据加载分页数据
    private int pageNumber = 0;
    //每次加载10条数据
    private int pageSize = 10;
    private boolean isFind = true;
    JhshBean mJhshBean;
    JhshSearchBean mSearchBean;

    public static boolean onStartRefresh = false;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        contentView = inflater.inflate(R.layout.fragment_jhshywc, container, false);
        mSHSwipeRefreshLayout = (SHSwipeRefreshLayout) contentView.findViewById(R.id.SHSwipeRefreshLayout);
        mSHListView = (SHListView) contentView.findViewById(R.id.SHListView);
        View FootView = inflater.inflate(R.layout.refresh_view, null);
        mFootTextView = (TextView) FootView.findViewById(R.id.title);
        mSHSwipeRefreshLayout.setFooterView(FootView);

        leftTextView = (TextView) contentView.findViewById(R.id.leftTextView);
        prev = (TextView) contentView.findViewById(R.id.prev);
        centerTextView = (TextView) contentView.findViewById(R.id.centerTextView);
        next = (TextView) contentView.findViewById(R.id.next);
        rightTextView = (TextView) contentView.findViewById(R.id.rightTextView);

        mJhshSearchView = (JhshSearchView) contentView.findViewById(R.id.jhshsearchview);
        mJhshSearchView.setZtlistFlag(JhshSearchView.SHYWC);
        InitData();
        InitSearchView();
        InitListen();
        return contentView;
    }


    @Override
    protected void InitData() {
        mList = new ArrayList<>();
        mSHListViewAdapter = new SHListViewAdapter();
        mSHListView.setAdapter(mSHListViewAdapter);
    }

    public void InitSearchView() {

        prev.setText("上一月");
        next.setText("下一月");

        mSearchBean = new JhshSearchBean();
        if (DateUtil.compare2Time("05") < 0) { //显示当前本月计划
            mSearchBean.setJhnyks(DateUtil.getYearAndMonth(date));
            mSearchBean.setJhnyjs(DateUtil.getYearAndMonth(date));
        } else { //显示次月计划
            mSearchBean.setJhnyks(DateUtil.getYearAndMonth(DateUtil.getAfterMonthDate(date, 1)));
            mSearchBean.setJhnyjs(DateUtil.getYearAndMonth(DateUtil.getAfterMonthDate(date, 1)));
            date = DateUtil.getAfterMonthDate(date, 1);
        }
//        mJhshSearchView.setDefaultDate(mSearchBean); //设置默认显示日期
        // 设置searchview默认显示日期
        centerTextView.setText(DateUtil.getYearAndMonth(date));
        mJhshSearchView.setConfirmListener(new JhshSearchView.OnClick() {
            @Override
            public void onConfirmListener(JhshSearchBean Util) {
                mSearchBean = Util;
                mSHSwipeRefreshLayout.startRefresh();
                RefreshAllDate(1, 10);
            }
        });
    }

    @Override
    protected void InitListen() {
        rightTextView.setOnClickListener(this);
        centerTextView.setOnClickListener(this);
        leftTextView.setOnClickListener(this);
        prev.setOnClickListener(this);
        next.setOnClickListener(this);

        mSHSwipeRefreshLayout.setOnRefreshListener(new SHSwipeRefreshLayout.SHSOnRefreshListener() {
            //下滑刷新 完成
            @Override
            public void onRefresh() {
                //下滑更新ListView内所有数据 包括高级查询在内   后三个参数分别为查询条件：施工日期 日计划号 相关单位编号
                RefreshAllDate(1, pageNumber * pageSize);
            }

            //上拉加载 完成
            @Override
            public void onLoading() {
                //加载更多数据
                LoadMoreDate();
            }

            /**
             * 监听下拉刷新过程中的状态改变
             * @param percent 当前下拉距离的百分比（0-1）
             * @param state 分三种状态{NOT_OVER_TRIGGER_POINT：还未到触发下拉刷新的距离；OVER_TRIGGER_POINT：已经到触发下拉刷新的距离；START：正在下拉刷新}
             */
            //下滑 刷新数据
            @Override
            public void onRefreshPulStateChange(float percent, int state) {
                switch (state) {
                    case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                        mSHSwipeRefreshLayout.setRefreshViewText("下拉刷新");
                        break;
                    case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                        mSHSwipeRefreshLayout.setRefreshViewText("松开刷新");
                        break;
                    case SHSwipeRefreshLayout.START:
                        mSHSwipeRefreshLayout.setRefreshViewText("正在刷新");
                        break;
                }
            }

            //上拉 加载更多数据
            @Override
            public void onLoadmorePullStateChange(float percent, int state) {
                switch (state) {
                    case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                        mFootTextView.setText("上拉加载");
                        break;
                    case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                        mFootTextView.setText("松开加载");
                        break;
                    case SHSwipeRefreshLayout.START:
                        mFootTextView.setText("正在加载...");
                        break;
                }
            }
        });
    }

    //页面第一次进入加载
    @Override
    protected void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
        RefreshAllDate(1, 10);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //日期选择
            case R.id.centerTextView:
                TimePickerView.getInstanceEndMonth(getContext(),JhshywcFragment.this.date,new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        JhshywcFragment.this.date=date;
                        setSearchBean();
                        upDatedAndRefresh();
                        RefreshAllDate(1, 10);
                    }
                }).show();
                break;
            case R.id.leftTextView:
                getActivity().finish();
                break;
            case R.id.rightTextView:
                if (mJhshSearchView.getVisibility() == View.GONE) {
                    mJhshSearchView.setVisibility(View.VISIBLE);
                } else {
                    mJhshSearchView.setVisibility(View.GONE);
                }
                break;
            case R.id.prev:
                butPrev();
                break;
            case R.id.next:
                butNext();
                break;
        }
    }

    //按钮上个月事件
    public void butPrev() {
        date = DateUtil.getAfterMonthDate(date, -1);
        setSearchBean();
        upDatedAndRefresh();
    }

    //按钮下个月事件
    public void butNext() {
        date = DateUtil.getAfterMonthDate(date, 1);
        setSearchBean();
        upDatedAndRefresh();
    }

    //更新标题栏日期并刷新列表数据
    public void upDatedAndRefresh() {
        centerTextView.setText(DateUtil.getYearAndMonth(date));
        //刷新列表数据
        RefreshAllDate(1, 10);
    }

    //设置搜索日期
    private void setSearchBean() {
        mSearchBean.setJhnyks(DateUtil.getYearAndMonth(date));
        mSearchBean.setJhnyjs(DateUtil.getYearAndMonth(date));
        //将搜索数据同步更新带搜索view当中
        mJhshSearchView.setDefaultDate(mSearchBean);
    }

    @Override
    public void onStart() {
        super.onStart();
        if (onStartRefresh) {
            RefreshAllDate(1, 10);
            onStartRefresh = false;
        }
    }

    @Override
    public boolean onBackPressed() { //处理自定义View，系统返回键
        if (mJhshSearchView.getVisibility() == View.VISIBLE) {
            mJhshSearchView.setVisibility(View.GONE);
            return true;
        } else {
            return BackHandlerHelper.handleBackPress(this);
        }
    }

    //加载审核已完成数据
    public void LoadMoreDate() {
        pageNumber++;
        Map<String, String> map = new HashMap<>();
        map = setParams(map, mSearchBean);
        map.put("pageNumber", String.valueOf(pageNumber));
        map.put("pageSize", String.valueOf(pageSize));
        map.put("loginDwId", MyApplication.getmLoginUser().getUserUnitId());

        NetWorkApi.getSgyjhShywcList(map, new BaseCallBack<JhshBean>() {
                    @Override
                    public void Success(Call<JhshBean> call, Response<JhshBean> response) {
                        try {
                            mJhshBean = response.body();

                            if (mJhshBean.getMsg().equals("success") && mJhshBean.getRows().size() == 0) {
//                                MyToast.showNoDate(getContext());
                            } else {
                                mList.addAll(mJhshBean.getRows());
                                mSHListViewAdapter.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void Failure(Call<JhshBean> call, Throwable t) {
                        MyToast.showFail();
                    }

                    @Override
                    public void onFinally() {
                        mSHSwipeRefreshLayout.finishLoadmore();
                    }
                }
        );
    }

    //更新当前加载的所有审核已完成数据
    public void RefreshAllDate(int pageNumber, int pageSize) {
        this.pageNumber = pageNumber;

        Map<String, String> map = new HashMap<>();
        map = setParams(map, mSearchBean);
        map.put("pageNumber", "1");
        map.put("pageSize", String.valueOf(pageNumber * pageSize));
        map.put("loginDwId", MyApplication.getmLoginUser().getUserUnitId());
        MyApplication.ShowWaitDialog(getContext());
        NetWorkApi.getSgyjhShywcList(map, new BaseCallBack<JhshBean>() {
                    @Override
                    public void Success(Call<JhshBean> call, Response<JhshBean> response) {
                        try {
                            mJhshBean = response.body();

                            if (mJhshBean.getMsg().equals("success")) {
                                mList = mJhshBean.getRows();
                                mSHListViewAdapter.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void Failure(Call<JhshBean> call, Throwable t) {
                        MyToast.showFail();

                    }

                    @Override
                    public void onFinally() {
                        mSHSwipeRefreshLayout.finishRefresh();
                    }
                }
        );
    }


    //设置搜索参数
    public Map<String, String> setParams(Map<String, String> map, JhshSearchBean Bean) {
        if (Bean != null) {
            if (Bean.getZt() != null) {
                if (Bean.getZt().equals("审核中")) {
                    map.put("searchState", "2");
                }
                if (Bean.getZt().equals("已超时")) {
                    map.put("searchState", "3");
                }
                if (Bean.getZt().equals("已下达")) {
                    map.put("searchState", "4");
                }
                if (Bean.getZt().equals("不同意")) {
                    map.put("searchState", "1");
                }
                if (Bean.getZt().equals("全部")) {
                    map.clear();
                }
            }
            if (Bean.getLb() != null && !Bean.getLb().equals("")) {
                map.put("searchSgLb", mSearchBean.getLb());
            }
            if (Bean.getJhh() != null && !Bean.getJhh().equals("")) {
                map.put("searchBh", mSearchBean.getJhh());
            }
            if (Bean.getXm() != null && !Bean.getXm().equals("")) {
                map.put("searchXlMc", mSearchBean.getXm());
            }
            if (Bean.getDwhbmId() != null) {
//                if (!MyApplication.getmLoginUser().getUserUnitType().equals("sgb") && !MyApplication.getmLoginUser().getUserUnitType().equals("jgcs"))
                map.put("searchDwId", mSearchBean.getDwhbmId());
            }
            if (Bean.getJhnyks() != null && !Bean.getJhnyks().equals("")) {
                map.put("searchStartMonth", mSearchBean.getJhnyks());
            }
            if (Bean.getJhnyjs() != null && !Bean.getJhnyjs().equals("")) {
                map.put("searchEndMonth", mSearchBean.getJhnyjs());
            }

            if (Bean.getSfzs() != null && !Bean.getSfzs().equals("")) {
                if (Bean.getSfzs().equals("主审")) {
                    map.put("searchSpcs", "1");
                }
                if (Bean.getSfzs().equals("非主审")) {
                    map.put("searchNotSpcs", "1");
                }
            }
        } else {
            if (DateUtil.compare2Time("05") < 0) { //显示当前本月计划
                map.put("searchStartMonth", DateUtil.getNowMonth());
                map.put("searchEndMonth", DateUtil.getNowMonth());
            } else { //显示次月计划
                map.put("searchStartMonth", DateUtil.getNextMonth());
                map.put("searchEndMonth", DateUtil.getNextMonth());
            }
        }
        return map;
    }

    private class SHListViewAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder mViewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.zsyjhview, null);
                mViewHolder = new ViewHolder();
                mViewHolder.yjhh = (TextView) convertView.findViewById(R.id.yjhh);
                mViewHolder.sgrq = (TextView) convertView.findViewById(R.id.sgrq);
                mViewHolder.lb = (TextView) convertView.findViewById(R.id.lb);
                mViewHolder.layout_blfh = (LinearLayout) convertView.findViewById(R.id.layout_blfh);
                mViewHolder.tablelayout = (LinearLayout) convertView.findViewById(R.id.tablelayout);
                mViewHolder.xm = (TextView) convertView.findViewById(R.id.xm);
                mViewHolder.hb = (TextView) convertView.findViewById(R.id.hb);
                mViewHolder.sgdd = (TextView) convertView.findViewById(R.id.sgdd);
                mViewHolder.sgxm = (TextView) convertView.findViewById(R.id.sgxm);
                mViewHolder.sgnr = (TextView) convertView.findViewById(R.id.sgnr);
                mViewHolder.sgjx = (TextView) convertView.findViewById(R.id.sgjx);
                mViewHolder.blfh = (TextView) convertView.findViewById(R.id.blfh);
                mViewHolder.sgdw = (TextView) convertView.findViewById(R.id.sgdw);
                mViewHolder.zt = (TextView) convertView.findViewById(R.id.zt);
                mViewHolder.mImageView = (ImageView) convertView.findViewById(R.id.mImageView);
                mViewHolder.tv_jhsh = (TextView) convertView.findViewById(R.id.tv_jhsh);
                mViewHolder.flagImg = (ImageView) convertView.findViewById(R.id.yue_flag);
                mViewHolder.btnShlc = (TextView) convertView.findViewById(R.id.btn_shlc);
                convertView.setTag(mViewHolder);
            } else {
                mViewHolder = (ViewHolder) convertView.getTag();
            }
            mViewHolder.yjhh.setText(mList.get(position).getBh());
            mViewHolder.sgrq.setText(mList.get(position).getExsgrq());
            mViewHolder.lb.setText(mList.get(position).getLb() + "类");
            if (mList.get(position).getLb().equals("B")) {
                mViewHolder.lb.setTextColor(getResources().getColor(R.color.colorTextB));
            } else if (mList.get(position).getLb().equals("C")) {
                mViewHolder.lb.setTextColor(getResources().getColor(R.color.colorTextC));
            }
            mViewHolder.xm.setText(mList.get(position).getXlmc());
            mViewHolder.hb.setText(mList.get(position).getXbmc());
            mViewHolder.sgdd.setText(mList.get(position).getSgdd());
            mViewHolder.sgxm.setText(mList.get(position).getXmmc());
            mViewHolder.sgnr.setText(mList.get(position).getNrmc());
            mViewHolder.sgjx.setText(mList.get(position).getJxmc());
            mViewHolder.blfh.setText(mList.get(position).getFhcsmc());
            mViewHolder.sgdw.setText(mList.get(position).getSgdwmc());
            //B类防御 根据该计划类型是否为B类 判断是否显示
            if (mList.get(position).getLb().equals("B")) {
                mViewHolder.layout_blfh.setVisibility(View.VISIBLE);
            } else {
                mViewHolder.layout_blfh.setVisibility(View.GONE);
            }
            mViewHolder.zt.setText(mList.get(position).getYjhCxState());
            //根据状态标识 1 5 为红色 其余为绿色
            if(mList.get(position).getYjhCxValue().equals("1")||mList.get(position).getYjhCxState().equals("5")){
                mViewHolder.zt.setTextColor(getContext().getResources().getColor(R.color.colorRed));
            } else {
                mViewHolder.zt.setTextColor(getContext().getResources().getColor(R.color.colorGreenTitle));
            }

            mViewHolder.btnShlc.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CheckInfoActivity.mRowsBean = mList.get(position);
                    Intent intent = new Intent(getActivity(), CheckInfoActivity.class);
                    intent.putExtra("flags", "flags");
//                    intent.putExtra("pos",position);
                    startActivity(intent);
                }
            });

            if (MyApplication.getmLoginUser().getUserUnitName() != null)
                if (mList.get(position).getSpcsmc().equals(MyApplication.getmLoginUser().getUserUnitName())) {
                    mViewHolder.tv_jhsh.setText("主审");
                    mViewHolder.tv_jhsh.setVisibility(View.VISIBLE);
                } else {
                    mViewHolder.tv_jhsh.setText("");
                    mViewHolder.tv_jhsh.setVisibility(View.GONE);
                }
            //默认颜色
            mViewHolder.flagImg.setImageResource(R.drawable.yue_lv);
            //不同意
            if (mList.get(position).getYjhCxValue() != null && mList.get(position).getYjhCxValue().equals("1")) {
                mViewHolder.flagImg.setImageResource(R.drawable.yue_hong); //红色
            }
            //已超时
            if (mList.get(position).getYjhCxValue() != null && mList.get(position).getYjhCxValue().equals("3")) {
                mViewHolder.flagImg.setImageResource(R.drawable.yue_hong); //红色
            }
            mViewHolder.tablelayout.setOnClickListener(new View.OnClickListener() {
                                                           @Override
                                                           public void onClick(View v) {
                                                               Map<String, String> map = new HashMap<>();
                                                               map.put("bh", mList.get(position).getBh());
                                                               MyApplication.ShowWaitDialog(getContext());
                                                               NetWorkApi.getZsyjhXx(map, new Callback<ShyjhxqBean>() {
                                                                           @Override
                                                                           public void onResponse(Call<ShyjhxqBean> call, Response<ShyjhxqBean> response) {
                                                                               try {
                                                                                   ShyjhxqBean Bean = response.body();
                                                                                   JhshCKActivity.ZsyjhxxShBean = Bean;
                                                                                   //跳转到详情页面
                                                                                   getContext().startActivity(new Intent(getContext(), JhshCKActivity.class));
                                                                               } catch (Exception e) {
                                                                                   MyToast.showFail();
                                                                               }
                                                                               MyApplication.HideWaitDialog();
                                                                           }

                                                                           @Override
                                                                           public void onFailure(Call<ShyjhxqBean> call, Throwable t) {
                                                                               MyToast.showFail();
                                                                           }
                                                                       }
                                                               );
                                                           }
                                                       }
            );
            return convertView;
        }
    }

    class ViewHolder {
        //月计划号
        TextView yjhh;
        //施工日期
        TextView sgrq;
        //类别
        TextView lb;
        //B类防御layout
        LinearLayout layout_blfh;
        LinearLayout tablelayout;
        //线名
        TextView xm;
        //行别
        TextView hb;
        //施工地点
        TextView sgdd;
        //施工项目
        TextView sgxm;
        //施工内容
        TextView sgnr;
        //施工机械
        TextView sgjx;
        //B类防护
        TextView blfh;
        //施工单位
        TextView sgdw;
        //状态
        TextView zt;
        //操作按钮图片
        ImageView mImageView, flagImg;
        private TextView tv_jhsh;
        TextView btnShlc;
    }
}

